<script>
	import GoEasy from './utils/goeasy-2.0.13.min.js'
	export default {
		globalData:{
			uploadUrl:{
				zuoye:'https://api.xiaoluerp.com/Jwteachertask/fileupload',
				touxiang:'https://api.xiaoluerp.com/Jwteacher/fileupload'
			},
			navbarHeight:0, // 导航栏高
			iosSafeBottom:0, // ios底部安全区域(px)
			screenHeight:0, //屏幕高
			baseUrl:"https://api.xiaoluerp.com",
			config:{
				max_image_size: 10485760,
				max_video_second: 10,
				max_video_size: 10485760,
				activity:{}
			},
			configStatic:{
				max_image_size: 10485760,
				max_video_second: 10,
				max_video_size: 10485760,
				activity:{}
			},
			userInfo:null,
			userJiGou:[],
			userJiGou_id:-1,
			isWxwork:false,
			open_userid:'', // 企业微信端用于验证码登录
			hudongImgList:[], //互动图片id字符串
			hudongFiles:[],
			goEasy: GoEasy.getInstance({
				host:"hangzhou.goeasy.io",  //若是新加坡区域：singapore.goeasy.io
				appkey:"BC-8d89071a4d0a47cca9cb72b33495dead",
				modules:['pubsub','im']//根据需要，传入‘pubsub’或'im’，或数组方式同时传入
			}),
			isConnect:false,
			connectInterval:null,
			unReadList:[],
			unReadListStatic:[],
			watchUnReadList:(app,callback)=>{
				var globalData = app.globalData;
				Object.defineProperty(globalData,"unReadList", {
				  configurable: true,
				  enumerable: true,
				  set: function (value) {
					console.log('执行set',value)
					callback(value)
				  },
				  get:function(){
					const app = getApp();
					console.log('执行get',app.globalData.unReadListStatic)
					return app.globalData.unReadListStatic;
				  }
				})
			},
			watchConfig:(app,callback)=>{
				var globalData = app.globalData;
				Object.defineProperty(globalData,"config", {
				  configurable: true,
				  enumerable: true,
				  set: function (value) {
					callback(value)
				  },
				  get:function(){
					const app = getApp();
					return app.globalData.configStatic;
				  }
				})
			},
			checkVideoUrl(url){
				let checkList_img = ['bmp','jpg','jpeg','png','tif','gif','pcx','tga','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','raw','WMF','webp','avif','apng','BMP','JPG','JPEG','PNG','TIF','GIF','PCX','TGA','EXIF','FPX','SVG','PSD','CDR','PCD','DXF','UFO','EPS','AI','RAW','WMF','WEBP','AVIF','APNG'];
				var checkList_video = ['avi', 'wma', 'rmvb', 'rm', 'flash', 'mp4', 'mid', '3gp','AVI', 'WMA', 'RMVB', 'RM', 'FLASH', 'MP4', 'MID', '3GP'];
				let s = url.split('.')
				if(checkList_video.indexOf(s[s.length-1])!= -1){
					return true
				}else{
					return false
				}
			}
		},
		onLaunch: function() {
			let iphoneType = ['iPhone X','iPhone1','iPhone13','iPhone12','iPhone11','iPhone10']
			let iosSafeBottom = 0;
			let systemInfo = uni.getSystemInfoSync();
			let statusBarHeight = systemInfo.statusBarHeight
			let navbarHeight = systemInfo.platform == 'ios' ? parseFloat(44 + statusBarHeight) : parseFloat(48 + statusBarHeight);
			for(let i of iphoneType){
				if(systemInfo.model.indexOf(i) != -1){
					iosSafeBottom = 34
				}
			}
			this.globalData.navbarHeight = navbarHeight
			this.globalData.iosSafeBottom = iosSafeBottom
			this.globalData.screenHeight = systemInfo.screenHeight
			this.globalData.isWxwork = checkWx()
			getConfig(this)
			console.log('App Launch',systemInfo)
		},
		onShow: function() {
			connectGroup(this);
			console.log('App Show')
		},
		onHide: function() {
			closeConnect(this);
			console.log('App Hide')
		},
	}
	
	function getConfig(_this){
		uni.request({
			url: _this.globalData.baseUrl + '/index/config',
			method:'GET', 
			header:{
				"Content-Type":"application/x-www-form-urlencoded"
			},
			success(e){
				console.log('config',e)
				let res = e.data
				if(res.code == 200){
					_this.globalData.config = res.data
					_this.globalData.configStatic = res.data
				}
			}
		})
	}
	
	function connectGroup(_this){
		_this.globalData.connectInterval = setInterval(async ()=>{
			if(_this.globalData.userInfo !== null){
				connectGoEasy(_this)
				clearInterval(_this.globalData.connectInterval);
			}
		},2000)
	}
	
	// 连接goEasy
	function connectGoEasy(_this){
		let userData = {
			avatar: _this.globalData.baseUrl + _this.globalData.userInfo.headimg,
			nickname: _this.globalData.userInfo.nickname
		}
		_this.globalData.goEasy.connect({
			id: 'js-'+ _this.globalData.userInfo.organ_id + '-' + _this.globalData.userInfo.id,
			data: userData,
			onSuccess: function(){
				console.log("GoEasy connect successfully.")
				subscribeGroup(_this);
				_this.globalData.isConnect = true;
			},
			onFailed: function(error){
				console.log("Failed to connect GoEasy, code:"+error.code+ ",error:"+error.content);
			},
			onProgress: function(attempts){
				// console.log("GoEasy is connecting", attempts);
			}
		});
	}
	
	// 订阅群消息
	function subscribeGroup(_this){ 
		const im = _this.globalData.goEasy.im;
		// 获取学生列表的聊天室id->订阅
		uni.request({
			url: _this.globalData.baseUrl + '/student',
			method:'POST', 
			header:{
				"Content-Type":"application/x-www-form-urlencoded"
			},
			data:{
				page:1,
				limit:9999,
				token:_this.globalData.userInfo.token
			},
			success(res) {
				if(res.data.code == 200){
					let groupIds = []
					for(let i of res.data.data){
						groupIds.push(i.xlchatid)
					}
					im.subscribeGroup({
						groupIds:groupIds,
						onSuccess: function () {  //订阅成功
						   console.log("Group message subscribe successfully.");
						   conversationsUpdated(_this); // 订阅成功开启监听会话列表
						},
						onFailed: function (error) { //订阅失败
						   console.log("Failed to subscribe group message, code:" + error.code + " content:" + error.content);
						}
					});
				}
			}
		})
	}
	
	// 监听会话列表变化
	function conversationsUpdated(_this){
		const im = _this.globalData.goEasy.im;
		var onConversationsUpdated = function(res) {
			console.log('onConversationsUpdated',res)
			let arr = [];
			for(let i of res.conversations){
				let obj = {
					groupId:i.groupId,
					unread:i.unread,
					content:i.lastMessage.payload.text,
					info:i.data
				}
				arr.push(obj)
			}
			_this.globalData.unReadList = JSON.parse(JSON.stringify(arr)) 
			_this.globalData.unReadListStatic = JSON.parse(JSON.stringify(arr)) 
		};
		//监听会话列表更新
		im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, onConversationsUpdated);
	}
	
	// 关闭连接
	function closeConnect(_this){
		_this.globalData.goEasy.disconnect({
			onSuccess: function(){
				console.log("GoEasy disconnect successfully.")
			},
			onFailed: function(error){
				console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
			}
		});
	}
	
	function checkWx(){ //判断是否为企业微信
		const info = wx.getSystemInfoSync()
		if(info.environment === "wxwork"){ //企业微信模式（仅在手机小程序端有此参数）
			return true
		}else{ // 普通微信登录
			return false
		}
	}
</script>

<style lang="scss">
	@import "uview-ui/index.scss";
	
	.acea-row {
		display: flex;
		flex-wrap: wrap;
	}
	
	.acea-row.row-top {
		align-items: flex-start;
	}
	
	.acea-row.row-middle {
		align-items: center;
	}
	
	.acea-row.row-bottom {
		align-items: flex-end;
	}
	
	.acea-row.row-left {
		justify-content: flex-start;
	}
	
	.acea-row.row-center {
		justify-content: center;
	}
	
	.acea-row.row-right {
		justify-content: flex-end;
	}
	
	.acea-row.row-between {
		justify-content: space-between;
	}
	
	.acea-row.row-around {
		justify-content: space-around;
	}
	
	.acea-row.row-column {
		flex-direction: column;
	}
	
	.acea-row.row-column-between {
		flex-direction: column;
		justify-content: space-between;
	}
	
	.acea-row.row-column-around {
		flex-direction: column;
		justify-content: space-around;
	}
	
	.acea-row.row-center-wrapper {
		align-items: center;
		justify-content: center;
	}
	
	.acea-row.row-between-wrapper {
		align-items: center;
		justify-content: space-between;
	}
	
	.line1 {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.line2{
		word-break: break-all;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}
	
	// 修改微信checkbox
	checkbox .wx-checkbox-input {
		background-color: #fafafa;
	}
	
	checkbox .wx-checkbox-input {
		border-radius: 50%;
		width: 38rpx;
		height: 38rpx;
	}
	
	checkbox .wx-checkbox-input.wx-checkbox-input-checked {
		border: 1px solid #e93323 !important;
		background-color: #e93323 !important;
		color: #fff !important;
	}
	
	checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
		font-size: 35rpx;
	}
	
	.bg-color{
		background-color: #e93323!important;
	}
	
	.font-color{
		color: #fc4141!important;
	}
	
	radio .wx-radio-input {
		border-radius: 50%;
		width: 38rpx;
		height: 38rpx
	}
	
	radio .wx-radio-input.wx-radio-input-checked {
		border: 1px solid #e93323!important;
		background-color: #e93323!important
	}
	
	radio .uni-radio-input {
		border-radius: 50%;
		width: 38rpx;
		height: 38rpx
	}
	
	radio .uni-radio-input.uni-radio-input-checked {
		border: 1px solid #e93323!important;
		background-color: #e93323!important
	}
	
	.c-footer{
		width: 100%;
		position: absolute;
		/* bottom: 132rpx; */
		bottom: calc(68rpx + var(--safe-area-inset-bottom));
		left: 0;
		text-align: center;
		font-size: 24rpx;
		color: #909399;
		line-height: 32rpx;
	}
	.c-footer text{
		color: #1661ff;
	}
	
	page {  
	    --safe-area-inset-top: 0px;  
	    --safe-area-inset-right: 0px;  
	    --safe-area-inset-bottom: 0px;  
	    --safe-area-inset-left: 0px;  
	
	}  
	
	@supports (top: constant(safe-area-inset-top)) {  
	    page {  
	        --safe-area-inset-top: constant(safe-area-inset-top);  
	        --safe-area-inset-right: constant(safe-area-inset-right);  
	        --safe-area-inset-bottom: constant(safe-area-inset-bottom);  
	        --safe-area-inset-left: constant(safe-area-inset-left);  
	    }  
	
	}  
	
	@supports (top: env(safe-area-inset-top)) {  
	    page {  
	        --safe-area-inset-top: env(safe-area-inset-top);  
	        --safe-area-inset-right: env(safe-area-inset-right);  
	        --safe-area-inset-bottom: env(safe-area-inset-bottom);  
	        --safe-area-inset-left: env(safe-area-inset-left);  
	    }  
	}  
	
	.commonFooter{
		// height: calc(32rpx + env(safe-area-inset-bottom));
		height: 32rpx;
	}
	.commonFooter2{
		height: calc(32rpx + env(safe-area-inset-bottom));
	}
</style>
